/**
 * 
 */
package string.passed2;

/**
 * @author xyyi
 *
 */
public class ZigZag {

	/*
	 ZigZag ConversionDec 6 '11

		The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
		
		P   A   H   N
		A P L S I I G
		Y   I   R
		
		And then read line by line: "PAHNAPLSIIGYIR"
		
		Write the code that will take a string and make this conversion given a number of rows:
		
		string convert(string text, int nRows);
		
		convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". 
		
		Solution
		http://98.210.100.205/wordpress/?p=90
		
	    1. Divide the string into sections;
	    2. For each row, iterate over all the sections:
	        if the row is at a zig (or zag), append the character to the return string;
	        if not, append the character and its counterpart in the same section. (For the last iteration, check if the counterpart exits.)
	    3. We can assert the return string has now the same number of characters as the input string.
	    4. Return the string.
	 */
    public String convert1(String s, int numRows) {
        if (s == null || s.isEmpty() || numRows <= 1)
            return s;
        
        StringBuilder sb = new StringBuilder();
        int sectionLen = (numRows - 1) * 2;
        
        for (int row = 0; row < numRows; row++) {
            for (int i = row; i < s.length(); i += sectionLen) {
                sb.append(s.charAt(i));
                int j = i + sectionLen - row * 2;
                if (j < s.length() && row != 0 && row != numRows - 1) {
                    sb.append(s.charAt(j));
                }
            }
        }
        
        return sb.toString();
    }
    
	public String convert(String s, int nRows) {
		if (s == null || s.isEmpty() || nRows <= 1)
			return s;

		int sectionSize = (nRows - 1) * 2;
		StringBuffer sb = new StringBuffer();

		for (int row = 0; row < nRows; row++) {
			if (row == 0 || row == nRows - 1) {
				for (int i = row; i < s.length(); i = i + sectionSize) {
					sb.append(s.charAt(i));
				}
			} else {
				for (int i = row; i < s.length(); i = i + sectionSize) {
					sb.append(s.charAt(i));
					int j = i + sectionSize - (row * 2);
					if (j < s.length())
						sb.append(s.charAt(j));
				}
			}
		}

		return sb.toString();
	}

	/**
	 * 
	 */
	public ZigZag() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
